package verbindung;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
 * 
 * @author Nilientes
 *
 */
public class DBDTransStruct {
	/**
	 * 
	 */
	public String name;
	/**
	 * 
	 */
	public int value;
	/**
	 * 
	 */
	public byte command;

	protected DBDTransStruct() {

	}

	protected DBDTransStruct(String name, int value, byte command) {
		super();
		this.name = name;
		this.value = value;
		this.command = command;
	}

	/**
	 * 
	 * @param out
	 * @throws IOException
	 */
	public void sendStruct(DataOutputStream out) throws IOException
	{
		if (name.length() > 15) Logger.getLogger(DBDTransStruct.class).error("Name ist to long for transsctruct");

		int ssize = out.size();
		
			byte[] b = new byte[4];
			b = intToByteArray(value);

			for (int i = 0; i < 4; i++)
				out.writeByte(b[i]);

			out.writeByte(command);
			for (int i = 0; i < 16; i++)
				if (i < name.length()) out.writeByte(name.charAt(i));
				else out.writeByte('\0');

			out.flush();

		

		Logger.getLogger(DBDTransStruct.class).info("sendStruct sends " + (out.size() - ssize)+" bytes");

	}

	/**
	 * 
	 * @param in
	 * @throws IOException
	 */
	public void receiveStruct(DataInputStream in) throws IOException
	{
		byte[] buf = new byte[21];

		Logger.getLogger(DBDTransStruct.class).info("sendStruct receives 21 bytes");
		
			in.read(buf);
		

		byte[] namebytes = new byte[16];
		byte[] valuebytes = new byte[4];

		for (int i = 0; i < 4; i++)
			valuebytes[i] = buf[i];

		value = byteArrayToInt(valuebytes);

		command = buf[4];
		for (int i = 0; i < 16; i++)
			namebytes[i] = buf[5 + i];

		name = new String(namebytes).replace("\0", "");

	}

	/**
	 * 
	 * @param b
	 * @return returns the integer that is represented by the byte array in Bigendian-Order
	 */
	private int byteArrayToInt(byte[] b)
	{
		int accum = 0;
		int i = 0;
		for (int shiftBy = 0; shiftBy < 32; shiftBy += 8) {
			accum |= ((int) (b[i] & 0xff)) << shiftBy;
			i++;
		}
		return accum;
	}

	// returns a byte array of length 4
	private byte[] intToByteArray(int i)
	{
		byte[] b = new byte[4];
		b[0] = (byte) (i & 0x00FF);
		b[1] = (byte) ((i >> 8) & 0x000000FF);
		b[2] = (byte) ((i >> 16) & 0x000000FF);
		b[3] = (byte) ((i >> 24) & 0x000000FF);
		return b;
	}

	@Override
	public String toString()
	{
		return "command: "+command+" var: '"+name+"' val: "+value;
	}
	
	
}
